package com.apes.framework.plugin.esb.processor.mapping.parser.element;

import com.apes.framework.plugin.esb.processor.mapping.parser.node.ConfigNodeParser;
import com.apes.framework.plugin.esb.processor.mapping.parser.model.Config;
import com.apes.framework.plugin.filereader.xml.ApesElement;
import com.apes.framework.plugin.filereader.xml.ApesElementParser;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Component;

import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 功能：config 元素解析器
 *
 * @author xul
 * @create 2018-04-16 14:25
 */
@Component
public class ConfigElementParser implements ApesElementParser<ApesElement, Config> {

    /**
     * 可解析的元素列表
     **/
    private final String[] elementNames = {"config", "nested"};

    /**
     * 功能：可解析节点域
     */
    @Override
    public String getDomain() {
        return ConfigNodeParser.domain;
    }

    /**
     * 功能：可解析的元素列表
     */
    @Override
    public String[] getNames() {
        return elementNames;
    }

    @Override
    public Config parse(ApesElement element) {
        Config config = new Config();
        element.getAttributes().forEach((k, v) -> {
            try {
                PropertyUtils.setSimpleProperty(config, k, v);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });

        config.setFields(element.getNestedElements().stream()
                .map(new Function<ApesElement, Object>() {
                    @Override
                    public Object apply(ApesElement nestedElement) {
                        return nestedElement.parse();
                    }
                }).collect(Collectors.toList()));
        return config;
    }


}
